package com.stox.ui.javafx.charting.model.plot;

import javafx.geometry.Side;

import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.stox.dto.AbstractModel;
import com.stox.dto.preference.PreferenceFactory;
import com.stox.ui.javafx.charting.model.ChartingPreference;
import com.stox.ui.javafx.charting.model.enumeration.VolumePlotPosition;
import com.stox.ui.javafx.charting.view.ChartingView;
import com.stox.ui.javafx.charting.widget.Chart;
import com.stox.ui.javafx.charting.widget.PrimaryChart;
import com.stox.ui.javafx.charting.widget.axis.AbstractVerticalAxis;
import com.stox.ui.javafx.charting.widget.axis.BlankVerticalAxis;
import com.stox.ui.javafx.charting.widget.axis.VolumeAxis;

@Component("volumePlot")
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class VolumePlot extends NumberPlot {

	private final ChartingView chartingView;
	
	private VolumePlotPosition volumePlotPosition;

	public VolumePlot(ChartingView chartingView, AbstractModel model) {
		super(model);
		this.chartingView = chartingView;
		setVolumePlotPosition(VolumePlotPosition.valueOf(PreferenceFactory.get(ChartingPreference.class).getVolumePlotPosition()));
	}

	public VolumePlotPosition getVolumePlotPosition() {
		return volumePlotPosition;
	}
	
	public void setVolumePlotPosition(VolumePlotPosition volumePlotPosition) {
		if(null != this.volumePlotPosition && this.volumePlotPosition.equals(volumePlotPosition)) return;
		this.volumePlotPosition = volumePlotPosition;
		refreshPosition();
	}
	
	public void refreshPosition() {
		PrimaryChart<?> primaryChart = chartingView.getPrimaryChart();
		if(null == primaryChart.getFrontPlot()) return;
		
		removeFromChart();
		setRightVerticalAxis(new BlankVerticalAxis());
		
		switch(volumePlotPosition) {
			case HIDDEN :
				break;
			case INDEPENDENT : 
				break;
			case PRICE_OVERLAY :
				addToChart(primaryChart);
		}
	}
	
	public VolumeAxis getVolumeAxis() {
		return getChart().getChartingView().getVolumeAxis();
	}
	
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public void addToChart(Chart chart) {
		chart.addPlot(this);
		setRightVerticalAxis(getVolumeAxis());
	}
	
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public void removeFromChart() {
		Chart chart = getChart();
		if(null == chart) return; 
		chart.removePlot(this);
	}
	
	private void setRightVerticalAxis(AbstractVerticalAxis abstractVerticalAxis) {
		Chart<?> chart = getChart();
		if(null == chart) return; 
		abstractVerticalAxis.setChart(chart);
		abstractVerticalAxis.setSide(Side.RIGHT);
		chart.setRightVerticalAxis(abstractVerticalAxis);
	}
	
}
